package string;

/**
 * 1.1 旋转字符串
 * <p/>
 * 题目描述
 * <p/>
 * 给定一个字符串，要求把字符串前面的若干个字符移动到字符串的尾部，如把字符串“abcdef”前面的2个字符'a'和'b'移动到字符串的尾部，使得原字符串变成字符串“cdefab”。请写一个函数完成此功能，要求对长度为n的字符串操作的时间复杂度为 O(n)，空间复杂度为 O(1)。
 * <p/>
 * https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/01.01.md
 * <p/>
 * Created by kail on 2016/9/11.
 */
public class RotationStringMain {

    private static char[] fanzhuan(final char[] chars, final int beginI, final int endI) {
        /**
         * 省略越界等判断
         */

        //  -------------------------

        char temp;
        int helfSize = (endI - beginI + 1) / 2;
        for (int beginIndex = beginI, i = 0; i < helfSize; beginIndex++, i++) {

            // 结尾索引
            int endIndex = endI - i;

            // 前后交换
            temp = chars[beginIndex];
            chars[beginIndex] = chars[endIndex];
            chars[endIndex] = temp;
        }
        return chars;
    }


    private static char[] fanzhuanK(char[] chars, final int k) {
        /**
         * 省略参数正确性等判断
         */
        //  -------------------------
        chars = fanzhuan(chars, 0, k - 1);
        chars = fanzhuan(chars, k, chars.length - 1);
        chars = fanzhuan(chars, 0, chars.length - 1);
        return chars;
    }


    public static void main(String[] args) {
        final String str = "123456789";
        char[] fanzhuan = fanzhuanK(str.toCharArray(), 2);
        System.out.println(fanzhuan);
    }

}
